

const query = getQuery()
const audio = document.querySelector('.audio')
let lrcArr = []
 
const renderLyric = list => {
  console.log(list)
  $('.lyric').innerHTML = list.map(item => `
    <div class="lyric-item">${item.text}</div>  
  `).join('')
}

const getLyric = async () => {
  const res = await request({
    url: `https://zyxcl.xyz/music/api/lyric?id=${query.id}`
  })
  lrcArr = res.lrc.lyric.split('\n').filter(Boolean).map(item => {
    const [time, text] = item.split(']')
    const [m, s] = time.slice(1).split(':')
    return {
      time: m * 60 + s * 1,
      text
    }
  })
  renderLyric(lrcArr)
}

const getComment = async () => {
  const res = await request({
    url: `https://zyxcl.xyz/music/api/comment/music?id=${query.id}`
  })
  // console.log('评论', res)
}

const getUrl = async () => {
  const res = await request({
    url: `https://zyxcl.xyz/music/api/song/url?id=${query.id}`
  })
  // console.log('播放地址', res.data[0].url)
  audio.src = res.data[0].url
}

const getSongDetail = async () => {
  const res = await request({
    url: `https://zyxcl.xyz/music/api/song/detail?ids=${query.id}`
  })
  // console.log('歌曲详情', res)
  $('.bg-img').style.backgroundImage = `url(${res.songs[0].al.picUrl})`
  $('.al-img img').src = res.songs[0].al.picUrl
  $('.song-info-name').innerHTML = res.songs[0].name
  $('.song-info-singer').innerHTML = res.songs[0].ar.map(v => v.name).join('/')
}



getLyric()
getComment()
getUrl()
getSongDetail()

// 绑定点击播放事件
$('.play-btn-wrap').addEventListener('click', () => {
  if (audio.paused) {
    audio.play()
    $('.play-btn').classList.remove('icon-bofang')
    $('.play-btn').classList.add('icon-zanting2')
    $('.black-circle').classList.add('running')
  } else {
    audio.pause()
    $('.play-btn').classList.remove('icon-zanting2')
    $('.play-btn').classList.add('icon-bofang')
    $('.black-circle').classList.remove('running')
  }
})

// 监听播放事件
audio.addEventListener('timeupdate', () => {
  const index = lrcArr.findIndex((v, i) => {
    if (i === lrcArr.length - 1) return true
    return audio.currentTime >= v.time && audio.currentTime < lrcArr[i + 1].time
  })
  $('.lyric-item.active')?.classList.remove('active')
  $all('.lyric-item')[index]?.classList.add('active')
  if ($all('.lyric-item')[index]) {
    $('.lyric').scrollTop = $all('.lyric-item')[index].offsetTop - 60
  }
})

// const str = '[01:13.23]我的心里没有任何的侥幸'

// { time: '01:13.23', text: '我的心里没有任何的侥幸' }